package com.hk.dyeyuesystem;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.hk.dyeyuesystem.db.DBOpenHelper;
import com.hk.dyeyuesystem.model.Book;
import com.hk.dyeyuesystem.util.DateUtil;
import com.hk.dyeyuesystem.util.RegexUtil;
import com.hk.dyeyuesystem.util.ToastUtil;

import java.util.Date;
import java.util.Objects;

/**
 * 图书更新相关操作
 */
public class BookUpdateActivity extends AppCompatActivity {

    //  Initialize Toast
    private Toast toast;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

    //    Initialize EditText Button
    private EditText bookNumber,bookName,bookAuthor,bookPress,bookCount;

    private Button bookUpdateBtn;


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_update);
//        实例化
        dbOpenHelper = new DBOpenHelper(BookUpdateActivity.this, "db_book_system", null, 1);
//        获取个EditText编辑框控制权
        bookNumber = findViewById(R.id.book_update_number);
        bookName = findViewById(R.id.book_update_name);
        bookAuthor = findViewById(R.id.book_update_author);
        bookPress = findViewById(R.id.book_update_press);
        bookCount = findViewById(R.id.book_update_count);
//        获取到Button的控制权
        bookUpdateBtn = findViewById(R.id.book_update_btn);
        //        提取出修改的值
        // TODO: 2021/12/21 提取出值，并进行更新(已完成)
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        echoBook(bundle);
        //        创建按钮点击事件
        bookUpdateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //                获取图书编号 新增数量
                String bookNumberToString = bookNumber.getText().toString();
//                新增数量
                String bookCountToString = bookCount.getText().toString();
//                更新作者
                String bookAuthorToString = bookAuthor.getText().toString();
//                更新出版社
                String bookPressToString = bookPress.getText().toString();
                // 校验图书各数据
                Boolean check = checkBookData(bookNumberToString,bookCountToString,bookAuthorToString,bookPressToString);
                if (check) { // 开始新增图书
                    SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//                    获取当前需要更新的原始数据
                    Cursor cursor = readableDatabase.query("BOOK", null, "BOOK_NUMBER = ?", new String[]{bookNumberToString}, null, null, null);
                    Book book = null;
                    while (cursor.moveToNext()) {
                        String bookNumber = cursor.getString(1);
                        String bookName = cursor.getString(2);
                        String auhtor = cursor.getString(3);
                        String press = cursor.getString(4);
                        Integer bookNum = null,bookRemaining = null;
                        try {
                            bookNum = Integer.valueOf(cursor.getString(5));
                            bookRemaining = Integer.valueOf(cursor.getString(6));
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                            Log.e("BookUpdateActivity.java","数据转化数字失败，请检查数据！");
                        }
//            通过构造函数封装数据
                        book = new Book(bookNumber,bookName,auhtor,press,bookNum,bookRemaining);
                    }
                    if (book == null) {
                        toast = ToastUtil.toastHint(toast,BookUpdateActivity.this,"未查到此数据,请刷新重试！");
                        return;
                    }
//                    封装需要更新的图书信息
                    ContentValues contentValues = new ContentValues();
                    contentValues.put("BOOK_NUM",(book.getbookNum()+Integer.parseInt(bookCountToString)));
                    contentValues.put("AUTHOR",bookAuthorToString);
                    contentValues.put("PRESS",bookPressToString);
                    contentValues.put("NUMBER_REMAINING",(book.getNumberRemaining()+Integer.parseInt(bookCountToString)));
                    contentValues.put("UPDATE_TIME", DateUtil.dateString(new Date()));
//                    执行新增图书
                    int update = readableDatabase.update("BOOK", contentValues, "BOOK_NUMBER = ?", new String[]{bookNumberToString});
                    if (update == 1) {
                        toast = ToastUtil.toastHint(toast, BookUpdateActivity.this, "图书更新成功，请返回进行查看！");
                        return;
                    }
                    toast = ToastUtil.toastHint(toast, BookUpdateActivity.this, "图书更新失败，请稍后重试！");
                    return;
                }
            }
        });

    }

    /**
     * 逐个校验数据是否符合规则
     * @param bookNumberToString  图书编号
     * @param bookCountToString 图书数量
     * @param bookAuthorToString 图书作者
     * @param bookPressToString  图书出版社
     * @return
     */
    private Boolean checkBookData(String bookNumberToString, String bookCountToString,String bookAuthorToString, String bookPressToString) {
//        校验图书编号
        if (bookNumberToString.equals("") || bookNumberToString.equals(null) || bookNumberToString == null) {
            toast = ToastUtil.toastHint(toast,BookUpdateActivity.this,"图书编号不能为空！");
            return false;
        }
//        校验图书作者和图书出版社
        if (RegexUtil.checkBlankSpace(bookAuthorToString)) {
            toast = ToastUtil.toastHint(toast,BookUpdateActivity.this,"图书作者不能包含空格！");
            return false;
        }
        if (RegexUtil.checkBlankSpace(bookPressToString)) {
            toast = ToastUtil.toastHint(toast,BookUpdateActivity.this,"出版社不能包含空格！");
            return false;
        }

//        开始校验数量
        if (bookCountToString.equals("") || bookCountToString.equals(null) || bookCountToString == null) {
            toast = ToastUtil.toastHint(toast,BookUpdateActivity.this,"数量不能为空！");
            return false;
        }
        if (RegexUtil.checkBlankSpace(bookCountToString)) {
            toast = ToastUtil.toastHint(toast,BookUpdateActivity.this,"数量不能包含空格！");
            return false;
        }
        if (!RegexUtil.checkDigitz(bookCountToString)) {
            toast = ToastUtil.toastHint(toast,BookUpdateActivity.this,"数量为正整数！");
            return false;
        }
        return true;
    }


    /**
     * 回显需要修改的数据原始信息
     * @param bundle 存储值传递对象
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void echoBook(Bundle bundle) {
        if (Objects.isNull(bundle)) {
            toast = ToastUtil.toastHint(toast,BookUpdateActivity.this,"获取对象信息,请重试！");
            return;
        }

        if (Objects.nonNull(bundle)) {
            String bookToString = (String) bundle.get("book");
            if (Objects.nonNull(bookToString)) {
                Book book = JSON.parseObject(bookToString,Book.class);
//                进行回显
                bookNumber.setText(book.getBookNumber());
                bookName.setText(book.getBookName());
                bookAuthor.setText(book.getAuhtor());
                bookPress.setText(book.getPress());
                return;
            }
            toast = ToastUtil.toastHint(toast,BookUpdateActivity.this,"获取对象信息,请重试！");
            return;
        }

    }


    /**
     * 重写onKeyDown()方法来拦截用户单击后退按钮事件
     * @param keyCode 按键标识
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        判断按下的是否为后退按键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            返回上一页标识是否刷新
//            setResult(RESULT_OK,new Intent());
            startActivityForResult(new Intent(BookUpdateActivity.this,BookAdminActivity.class),RESULT_OK);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}